package org.csu.question.service;

import org.csu.question.entity.dto.*;
import org.csu.question.entity.po.AnswerRecord;
import org.csu.question.entity.po.Questions;
import org.csu.question.mapper.AnswerRecordMapper;
import org.csu.question.mapper.KnowledgePointMapper;
import org.csu.question.mapper.QuestionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class QuestionService {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private AnswerRecordMapper answerRecordMapper;

    @Autowired
    private KnowledgePointMapper knowledgePointMapper;

    @Autowired
    private QuestionRecommendationService recommendationService;

    /**
     * 提交答案
     */
    public AnswerResultDTO submitAnswer(SubmitAnswerRequest request) {
        // 1. 查询题目
        Questions question = questionMapper.selectById(request.getQuestionId());
        if (question == null) {
            throw new RuntimeException("题目不存在");
        }

        // 2. 判断答案是否正确
        boolean isCorrect = question.getAnswer().equals(request.getUserAnswer());

        // 3. 保存答题记录
        AnswerRecord record = new AnswerRecord();
        record.setUserId(request.getUserId());
        record.setQuestionId(request.getQuestionId());
        record.setUserAnswer(request.getUserAnswer());
        record.setIsCorrect(isCorrect);
        record.setTimeCost(request.getTimeCost());

        answerRecordMapper.insert(record);

        // 4. 清除推荐缓存
        recommendationService.clearUserRecommendCache(request.getUserId());

        // 5. 返回结果
        AnswerResultDTO result = new AnswerResultDTO();
        result.setIsCorrect(isCorrect);
        result.setCorrectAnswer(question.getAnswer());
        result.setExplanation(question.getExplanation());
        result.setTimeCost(request.getTimeCost());

        return result;
    }

    /**
     * 获取用户答题统计
     */
    public UserStatsDTO getUserStats(Long userId) {
        List<KnowledgePointStats> stats = answerRecordMapper.selectUserKnowledgePointStats(userId);

        UserStatsDTO userStats = new UserStatsDTO();

        // 计算总体统计
        long totalQuestions = stats.stream().mapToLong(KnowledgePointStats::getTotalCount).sum();
        long correctQuestions = stats.stream().mapToLong(KnowledgePointStats::getCorrectCount).sum();
        double correctRate = totalQuestions > 0 ? (double) correctQuestions / totalQuestions : 0.0;

        userStats.setTotalQuestions(totalQuestions);
        userStats.setCorrectQuestions(correctQuestions);
        userStats.setCorrectRate(correctRate);

        // 转换知识点统计
        Map<String, KnowledgePointStatsDTO> knowledgePointStats = stats.stream()
                .collect(Collectors.toMap(
                        KnowledgePointStats::getTag,
                        stat -> {
                            KnowledgePointStatsDTO dto = new KnowledgePointStatsDTO();
                            dto.setName(stat.getKnowledgePointName());
                            dto.setTag(stat.getTag());
                            dto.setTotalCount(stat.getTotalCount().intValue());
                            dto.setCorrectCount(stat.getCorrectCount().intValue());
                            dto.setCorrectRate(stat.getCorrectRate());
                            return dto;
                        }
                ));

        userStats.setKnowledgePointStats(knowledgePointStats);

        return userStats;
    }
}
